package com.originskyseed.platform.user.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.role.model.Role;
import com.originskyseed.platform.role.model.RoleRelUser;
import com.originskyseed.platform.role.service.IRoleRelUserService;
import com.originskyseed.platform.role.service.IRoleService;
import com.originskyseed.platform.user.i18n.RegisterResponseMsg;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Staff;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IStaffService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.StaffRequestVO;

/**
 * 员工信息Controller类（OSI_STAFF）
 * 
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/staff")
@BaseLocaleResource(localeFileName = "i18n_user")
public class StaffController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(StaffController.class);

	@DubboReference
	private IStaffService staffService;

	@DubboReference
	private IUserInfoService userInfoService;

	@DubboReference
	private IRoleService roleService;

	@DubboReference
	private IRoleRelUserService roleRelUserService;

	/**
	 * 分页查询
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/staffList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Staff>> staffList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Staff>> result = null;
		try {
			// 请求对象
			StaffRequestVO requestVO = this.getParameterBean(StaffRequestVO.class);

			// 分页查询
			BasePage<Staff> page = new BasePage<Staff>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.staffService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<Staff>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Staff>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/staffSave.json", method = RequestMethod.POST)
	public BaseResponseBody<Staff> staffSave(HttpServletRequest request) {
		BaseResponseBody<Staff> result = null;
		try {
			// 请求对象
			Staff staff = this.getParameterBean(Staff.class);
			UserInfo userInfo = this.getParameterBean(UserInfo.class);
			userInfo.setId(staff.getUserId());

			// 判断账号是否符合规则
			if (!userInfo.getAccount().matches("^[0-9A-Za-z]{16}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_RULE_ERROR.getMsg()), false);
			}
			// 判断账号是否存在
			if (userInfoService.accountExist(userInfo)) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.ACCOUNT_EXIST.getMsg()), false);
			}

			// 判断密码
			if (userInfo.getPassword().length() < 8) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_LENGTH_ERROR.getMsg()), false);
			} else if (!userInfo.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z!@#$%^&*,\\.]{8,64}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
			}

			if (StringUtils.isNotBlank(staff.getId())) {
				userInfo.setPassword(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
				this.staffService.updateByPrimaryKeySelective(staff, userInfo);
			} else {
				staff.setStaffNum(this.staffService.selectStaffNum());
				userInfo.setPassword(DigestUtils.md5DigestAsHex(userInfo.getPassword().getBytes()));
				this.staffService.insertSelective(staff, userInfo);
			}
			result = new BaseResponseBody<Staff>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), staff);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Staff>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/staffDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> staffDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.staffService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectStaffById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectStaffById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			Staff staff = this.staffService.selectByPrimaryKey(id);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), staff);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改部门状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateStatus.json")
	@RequiredParams(names = { "ids", "status" })
	public BaseResponseBody updateStatus(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String[] ids = this.getParameterArray("ids", null);
			Integer status = this.getParameterInteger("status", null);
			Map<String, Object> map = new HashMap<>();
			map.put("list", Arrays.asList(ids));
			map.put("status", status);
			this.staffService.updateStatusByIds(map);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改部门状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updatePassword.json")
	@RequiredParams(names = { "id", "password" })
	public BaseResponseBody updatePassword(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			String password = this.getParameterString("password", null);
			UserInfo userInfo = this.userInfoService.selectByPrimaryKey(id);
			// 判断密码
			if (userInfo.getPassword().length() < 8) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_LENGTH_ERROR.getMsg()), false);
			} else if (!userInfo.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z!@#$%^&*,\\.]{8,64}$")) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
			} else if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(userInfo.getPassword())) {
				return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.NEW_OLD_PASSWORD_AGREEMENT.getMsg()), false);
			}

			UserInfo updateUserInfo = new UserInfo();
			updateUserInfo.setId(id);
			updateUserInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
			updateUserInfo.setUpdateTime(new Date());
			updateUserInfo.setUpdatePassTime(new Date());
			this.userInfoService.updateByPrimaryKeySelective(updateUserInfo);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 用户绑定角色页面
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userInfoBindRoleList.json")
	public BaseResponseBody userInfoBindRoleList(HttpServletRequest request) {
		BaseResponseBody result = null;
		Map<String, Object> model = new HashMap<String, Object>();
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			if (StringUtils.isNotBlank(id)) {
				UserInfo userInfo = this.userInfoService.selectByPrimaryKey(id);
				model.put("userInfo", userInfo);
				Role role = new Role();
				List<Role> roleList = this.roleService.selectList(role);
				model.put("roleList", roleList);
				List<RoleRelUser> roleRelUserList = this.roleRelUserService.selectByUserId(id);
				model.put("roleRelUserList", roleRelUserList);
				result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), model);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 用户信息绑定角色
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/userInfoBindRole.json")
	@RequiredParams(names = { "userId" })
	public BaseResponseBody userInfoBindRole(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String userId = this.getParameterString("userId", null);
			String[] roleIds = this.getParameterArray("roleIds", new String[] {});

			List<String> roleIdList = Arrays.asList(roleIds);
			this.roleRelUserService.deleteAndInsertByUserId(userId, roleIdList);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}
}